package cn.wwxula.user.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.wwxula.common.properties.JwtProperties;
import cn.wwxula.common.util.JwtUtil;
import cn.wwxula.user.constant.UserConstant;
import cn.wwxula.user.holder.UserHolder;
import cn.wwxula.user.model.entity.User;
import cn.wwxula.user.service.UserService;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author liyang23
 * @date 2024/12/17 19:29
 **/
@Component
@Slf4j
public class UserHolderInterceptor implements HandlerInterceptor {
    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("[用户服务] 正在保存调用者信息");
        String userToken = request.getHeader(jwtProperties.getUserTokenName());
        if (StrUtil.isBlank(userToken) ) {
            return false;
        }
            Claims claims = JwtUtil.parseJwt(jwtProperties.getUserSecretKey(), userToken);
            Long userId = (Long) claims.get(UserConstant.USER_ID);
            User user = userService.getById(userId);
            UserHolder.saveUser(user);
        return true;
    }
}
